// 路由鉴权,
import router from "./index.js";
// 获取仓库:因为permission实在main.js里面直接引用的，所以在先引入大仓库才能用小仓库
import pinia from "@/store/index.js";
import loginStore from "@/store/login/index.js";
let $loginStore = loginStore(pinia);


// 路由进步条：
// 下载进度条插件：cnpm i nprogress
// 引入进度条
import NProgress from "nprogress";
// 进入进度条样式
import "nprogress/nprogress.css";
NProgress.configure({
  showSpinner: false
})
// 全局前置守卫
// to:你去哪，from:你从哪来,next:路由放行跳转到哪里

router.beforeEach(async (to, from, next) => {
  // 进度条开始
  NProgress.start();

  // console.log(router, 'to.path')
  const whiteList = ['/auth-bind-wx', '/auth-bind-success', '/login', '/auth-redirect']
  let token = $loginStore.token;
  let user_info = $loginStore.user_info;

  if (whiteList.indexOf(to.path) !== -1) {
    localStorage.clear();

    next();
  } else {
    if (token) {
      // await $loginStore.userInfo()
      if (user_info) {
        next();
      } else {
        try {

          await $loginStore.userInfo()
          // next();
          next({
            ...to,
            replace: true
          })
          // console.log('路由守卫')
        } catch {
          localStorage.clear();
          next({
            path: '/login',
          })
        }


      }

    } else {
      localStorage.clear();
      next({
        path: '/login'
      })
    }
  }
});

// 全局后置守卫
router.afterEach((to, form) => {
  document.title = '单位后台管理系统' + "-" + to.meta.title;
  NProgress.done();
});
